import qs from 'qs';
import {
  DataProcessGetFolder,
  DataProcessInsertLevel,
  DataProcessDeleteLevel,
  DataProcessUpdateLevel
} from "@/api/stu/datahandle"
import { ref, reactive, nextTick, onMounted } from "vue"
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { emitter } from "@/utils/mitt";
export function usehooks() {
  const loading = ref(false)
  const Visible = ref(false)
  const Visibletitle = ref("添加")
  const dataList = ref<any>([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 1000,
    currentPage: 1,
    background: true
  });
  const refform = ref()
  const isdata = ref([])
  const form = reactive({
    id: "",
    parent: "0",
    parentId: "",
    folderName: "",
    dataprocessFolderId: ""
  })
  const rules = {
    parent: [
      {
        required: true,
        message: "请选择父级！",
        trigger: ["blur", "change"]
      }
    ],
    folderName: [
      {
        required: true,
        message: "请输入名称！",
        trigger: ["blur", "change"]
      }
    ],
  }

  // firstdata
  function firstdata(items) {
    let result = [];
    items.forEach((item) => {
      if (Array.isArray(item.child)) {
        result = result.concat(firstdata(item.child))
      } else {
        result.push(item)
      }
    })
    return result;
  }
  // 修改
  // 将所有child的数据合到一个数组里让修改的数据可以获取到父节点

  function AddData(row) {
    (row as any).validate(async valid => {
      if (!valid) return;
      let res: any;
      if (form.dataprocessFolderId == '') {
        const data = {
          folderName: form.folderName,
          parentId: form.parent
        }
        res = await DataProcessInsertLevel(data);
      } else {
        const data = {
          dataprocessFolderId: form.dataprocessFolderId,
          folderName: form.folderName,
          parentId: form.parentId
        }
        res = await DataProcessUpdateLevel(data);
      }
      if (res.success) {
        ElMessage.success(res.msg)
        GetDataList()
        CloseData(refform.value)
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 打开窗口
  function HandEdit(row: any) {
    Visible.value = true;
    console.log("Edit", row)
    if (row) {
      nextTick(() => {
        Visibletitle.value = "修改"
        form.parent = row.parentId || row.id;
        form.folderName = row.folderName;
        form.dataprocessFolderId = row.id
        form.parentId = row.parentId
      })
    } else {
      Visibletitle.value = "添加";
      form.dataprocessFolderId = ""
    }
  }

  // 删除
  async function HandDelete(row: any) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const data = qs.stringify({
        DataprocessFolderId: row.id,
      });
      const res = await DataProcessDeleteLevel(data);
      if (res.success) {
        GetDataList()
        ElMessage.success(res.msg)
      }
      else ElMessage.error(res.msg)
    }).catch(() => { })
  }


  async function CloseData(row) {
    row.resetFields()
    Visible.value = false;
  }

  // 获取数据列表
  async function GetDataList() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize
    };
    const res = await DataProcessGetFolder(data);
    // 添加时
    const first = {
      createTime: "",
      folderName: "首级",
      parentId: "0",
      child: [],
      id: "0"
    }
    if (res.success) {
      pagination.total = res?.data?.total;
      dataList.value = [...res?.data?.items, ...[first]];
      console.log("isArray", firstdata(dataList.value))
    } else {
      ElMessage.error(res.msg)
    }
  }

  onMounted(() => {
    GetDataList()
  })
  return {

    form,
    rules,
    refform,
    Visible,
    loading,
    dataList,
    pagination,
    Visibletitle,
    AddData,
    CloseData,
    HandEdit,
    HandDelete
  }
}
